package tianxiao.web.test.common;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.stereotype.Component;
import tianxiao.web.test.common.exception.CommonException;
import yun.web.activerecord.ActiveRecordException;
import yun.web.springmvc.GlobalExceptionHandlerItf;
import yun.web.springmvc.ext.MvcWriteException;
import yun.web.springmvc.ext.MvcWriteUtil;
import yun.web.springmvc.paramcheck.ParamCheckException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class GlobalExceptionHandlerImpl implements GlobalExceptionHandlerItf {
    Log log = LogFactory.get("GlobalExceptionHandlerImpl");

    @Override
    public void handleException(HttpServletRequest req, HttpServletResponse resp, Throwable e) {
        log.error(e);
        if (e instanceof ActiveRecordException) {
            resp.setStatus(200);
        }
        // 如果出现了MvcWriteException , 意味着写客户端失败了.
        // 可能是客户端连接强制断开(比如关了网页 断网, 这时候便不能继续使用resp对象
        // 也可能是你要写入的文件路径搞错了, 抛出的异常
        else if (e instanceof MvcWriteException) {

        }
        // @ParamCheck 指定的方法执行时发生异常, 将抛出 ParamCheckException
        else if (e instanceof ParamCheckException) {

        }
        //
        else if (e instanceof CommonException) {
            MvcWriteUtil.write(req, resp, new CommonException.CommonExceptionResult(e.getMessage()));
        } else {
            resp.setStatus(500);
        }
    }
}
